package blue.http.core.filter;

import blue.http.core.annotation.Filter;
import blue.http.core.message.HttpRequest;
import blue.http.core.message.HttpResponse;
import blue.http.core.message.UploadFile;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.Map;

/**
 * @author Jin Zheng
 * @since 1.0 2020-01-08
 */
@Filter(filters = "/**", order = 1)
public class UploadFileFilter implements HttpFilter {
	private static Logger logger = LoggerFactory.getLogger(UploadFileFilter.class);

	public UploadFileFilter() {
	}

	@Override
	public void afterCompletion(HttpRequest request, HttpResponse response, Exception ex) throws Exception {
		Map<String, UploadFile> fileMap = request.getFileMap();
		if (fileMap == null || fileMap.isEmpty()) {
			return;
		}

		for (Map.Entry<String, UploadFile> entry : fileMap.entrySet()) {
			UploadFile uploadFile = entry.getValue();
			if (uploadFile == null || uploadFile.getPath() == null) {
				continue;
			}

			Path path = uploadFile.getPath();
			try {
				boolean result = Files.deleteIfExists(path);
				String strResult = result ? "Success" : "Failure";
				logger.info("delete file: {} - {}", strResult, uploadFile);
			} catch (IOException e) {
				logger.warn("delete file error, ", e);
			}
		}
	}
}
